﻿var gUserLoginResult;   // 用户登录后信息，详细内容见文档
var gMainDT;            // 页面主DataTables表格
var gInsert = 0;        // 每个页面的增加功能权限
var gDelete = 0;        // 每个页面的删除功能权限
var gUpdate = 0;        // 每个页面的修改功能权限
var gSelect = 0;        // 每个页面的查询功能权限
var gCheck = 0;         // 每个页面的审核功能权限
var gActorNames;        //登录用户的角色
var gRoadsignId = 0;      //维修记录中的故障路牌Id
var gPoint;                 //获取当前位置

var mouseStartPoint = {"left": 0, "top": 0};
var mouseEndPoint = {"left": 0, "top": 0};
var mouseDragDown = false;
var oldP = {"left": 0, "top": 0};
var moveTartet;

var gDeviceState=["离线","在线","故障"]
var gColor=["#999","#00a65a","#dd4b39"]


$(function () {

    //dataTable弹框报错改为控制台报错
    $.fn.dataTable.ext.errMode = function (s, h, m) {
    };

    //模态框移动，复位
    $(document).on("show.bs.modal", ".modal", function () {
        $(this).find(".modal-content").css({"top": "0px", "left": "0px"});
        $(this).find(".modal-dialog").css({"top": "0px", "left": "0px"});
    });

    $(document).on("mousedown", ".modal-header", function (e) {
        if ($(e.target).hasClass("close"))//点关闭按钮不能移动对话框
            return;
        mouseDragDown = true;
        moveTartet = $(this).parent().parent();
        mouseStartPoint = {"left": e.clientX, "top": e.clientY};
        oldP = moveTartet.offset();
    });

    $(document).on("mouseup", function (e) {
        mouseDragDown = false;
        moveTartet = undefined;
        mouseStartPoint = {"left": 0, "top": 0};
        oldP = {"left": 0, "top": 0};
    });

    $(document).on("mousemove", function (e) {
        if (!mouseDragDown || moveTartet == undefined) return;
        var mousX = e.clientX;
        var mousY = e.clientY;
        if (mousX < 0) mousX = 0;
        if (mousY < 0) mousY = 5;
        mouseEndPoint = {"left": mousX, "top": mousY};
        var width = moveTartet.width();
        var height = moveTartet.height();
        mouseEndPoint.left = mouseEndPoint.left - (mouseStartPoint.left - oldP.left);//移动修正，更平滑
        mouseEndPoint.top = mouseEndPoint.top - (mouseStartPoint.top - oldP.top);
        moveTartet.offset(mouseEndPoint);
    });

    // 全局异步异常处理
    $.ajaxSetup({
        type: 'POST',
        complete: function (xhr, status) {
            var sessionStatus = xhr.getResponseHeader('sessionstatus');
            if (sessionStatus == 'timeout') {
                bootbox.confirm({
                    buttons: {
                        confirm: {
                            label: '<i class="fa fa-check"></i> 确定',
                            className: 'btn btn-primary btn-flat'
                        },
                        cancel: {
                            label: '<i class="fa fa-close"></i> 取消',
                            className: 'btn btn-warning btn-flat pull-left'
                        }
                    },
                    message: '<i class="fa fa-question-circle-o"></i> ' +
                    '<b class="customer-title">由于您长时间没有操作，Session已过期，请重新登录</b>',
                    callback: function (result) {
                        if (result) {
                            sessionStorage.clear();
                            window.location.replace("../login.html");
                        }
                    }
                });
            }
        }
    });
    // 获取登录后的参数信息
    if (!sessionStorage.rdsUserLoginResult) {
        window.location.replace("../login.html");
    } else {
        gUserLoginResult = JSON.parse(sessionStorage.rdsUserLoginResult);

        if (sessionStorage.rdsTree == null || sessionStorage.rdsTree == "")
            $("#sidebar-menu").html("<div class='overlay text-center'>" +
                "<i class='fa fa-frown-o fa-2x text-primary'></i> " +
                "<b>权限不足</b></div>");
        else
            $("#sidebar-menu").html(sessionStorage.rdsTree);

        $.getActorNameByUserId();
        $("#orgName").text(gUserLoginResult.orgName);
        $("#myLoginTime").html(gUserLoginResult.userLoginTime);
        $("#myName-middle").html(gUserLoginResult.userName);
        $("#myName-small").html(gUserLoginResult.userName);
        if (gUserLoginResult.userIcon == "" || gUserLoginResult.userIcon == null) {
            if (gUserLoginResult.userSex == "男") {
                $("#myPhoto-large").attr('src', src = "../images/default_male.png");
                $("#myPhoto-middle").attr('src', src = "../images/default_male.png");
                $("#myPhoto-small").attr('src', src = "../images/default_male.png");
            } else {
                $("#myPhoto-large").attr('src', src = "../images/default_female.png");
                $("#myPhoto-middle").attr('src', src = "../images/default_female.png");
                $("#myPhoto-small").attr('src', src = "../images/default_female.png");
            }
        } else {
            $("#myPhoto-large").attr('src', src = gUserLoginResult.userIcon);
            $("#myPhoto-middle").attr('src', src = gUserLoginResult.userIcon);
            $("#myPhoto-small").attr('src', src = gUserLoginResult.userIcon);
        }
        switch (sessionStorage.outType) {
            case "1":
                setTimeout(function () {
                    $.loadURL('设备管理', '管理地图', 'management/roadSignMap.html', 1, 1, 1, 1, 1);
                }, 1000);
                break;
            case "10":
                $.loadURL('系统管理', '用户管理', 'system/user.html', 1, 1, 1, 1, 1);
                break;
            case "11":
                $.loadURL('公告管理', '公告列表', 'notice/noticeList.html', 1, 1, 1, 1, 1);
                break;
            case "12":
                $.loadURL('个人中心', '信息修改', 'myinfo.html', 1, 1, 1, 1, 1);
                break;
            case "13":
                $.loadURL('设备管理', '报警器管理', 'management/alarmManage.html', 1, 1, 1, 1, 1);
                break;
            default:
                $.loadURL('首页', '首页', 'index.html', 1, 1, 1, 1, 1);
        }
    }
});

//根据用户id获取用户角色
$.getActorNameByUserId = function () {
    $.ajax({
        url: '../rds_user/getActorNameByUserId',
        type: 'post',
        data: {'userId': gUserLoginResult.userId},
        dataType: 'json',
        success: function (msg) {
            if (msg.isSuccess == true) {
                gActorNames = msg.jsonData;
                $("#myRole").html(gActorNames);
            }
        }
    });
};

//获取当前用户所在城市 用于地图展示定位
function myFun(result) {
    gPoint = result.name;
}

var myCity = new BMap.LocalCity();
myCity.get(myFun);


// 点击菜单加载页面
$.loadURL = function (first, second, url, powerInsert, powerDelete, powerUpdate, powerSelect, powerCheck) {
    $("#menu-first").html(first);
    $("#menu-second").html(second);
    $("#workbench").load(url);
    gInsert = powerInsert;
    gDelete = powerDelete;
    gUpdate = powerUpdate;
    gSelect = powerSelect;
    gCheck = powerCheck;
};

// 显示修改密码
$.modifyUserPwd = function () {
    $(".myInput").attr("disabled", false);
    $(".myInput").attr("readonly", false);
    $("#userId").val(gUserLoginResult.userId);
    $("#modal-pwd").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

// 修改密码
$('#form-pwd').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        oldPwd: {
            validators: {
                notEmpty: {message: '密码不能为空'},
                regexp: {regexp: /^[a-zA-Z0-9_\.]+$/, message: '只能是字母、数字和下划线'},
                stringLength: {min: 6, max: 30, message: '密码长度必须在6到30之间'}
            }
        },
        newPwd: {
            validators: {
                notEmpty: {message: '密码不能为空！'},
                regexp: {regexp: /^[a-zA-Z0-9_\.]+$/, message: '只能是字母、数字和下划线'},
                stringLength: {min: 6, max: 30, message: '密码长度必须在6到30之间'},
                different: {field: 'oldPwd', message: '新旧密码不能相同'}
            }
        },
        confirmPwd: {
            validators: {
                notEmpty: {message: '密码不能为空'},
                regexp: {regexp: /^[a-zA-Z0-9_\.]+$/, message: '只能是字母、数字和下划线'},
                stringLength: {min: 6, max: 30, message: '密码长度必须在6到30之间'},
                identical: {field: 'newPwd', message: '两次密码不一致'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    $("input[name='userId']").val(gUserLoginResult.userId);
    var $form = $(e.target);
    $.ajax({
        url: '../rds_user/updatePwdById',
        type: 'post',
        data: $form.serialize(),
        dataType: 'json',
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess == true) {
                    if (msg.jsonData > 0) {
                        $.alert("密码修改成功", 1);
                        $.clearModal($('#form-pwd'), $('#modal-pwd'));
                    } else {
                        $.alert("原密码错误，请重新输入", 4);
                    }
                } else {
                    $.alert("修改失败", 4);
                    $.clearModal($('#form-pwd'), $('#modal-pwd'));
                }
            } else {
                $.alert('系统错误', 4);
                $.clearModal($('#form-pwd'), $('#modal-pwd'));
            }
        },
        error: function (msg) {
            $.alert('系统错误', 4);
            $.clearModal($('#form-pwd'), $('#modal-pwd'));
        }
    });
});

// 用户注销
$.logoutSystem = function () {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定退出系统?</b>',
        callback: function (result) {
            if (result) {
                sessionStorage.clear();
                window.location.replace("../login.html");
            }
        }
    });
};

//#############以下为全局js函数#############
//***************************************
// 自定义信息提示框
// alertContent: 内容
// alertType: 1--绿色(成功) 其他数字--红色(失败)
//***************************************
$.alert = function (alertContent, alertType) {
    $("#alertDiv").remove();
    $("body").append("<div id='alertDiv' style='position:fixed;top:100px;width:24%;margin-left:38%;z-index:1500;display:none;'><div id='alertContent' style='padding:10px;' class='alert text-center'></div></div>");
    if (alertType == 1) {
        $("#alertContent").html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button><b class='customer-title'><span class='glyphicon glyphicon-ok-sign'></span> " + alertContent + "</b>");
        $("#alertDiv").fadeIn();
        $("#alertContent").addClass("alert-success");
        $("#alertDiv").delay(1500).hide(0, function () {
            $(this).remove();
        });
    } else {
        $("#alertContent").html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button><b class='customer-title'><span class='glyphicon glyphicon-info-sign'></span> " + alertContent + "</b>");
        $("#alertDiv").fadeIn();
        $("#alertContent").addClass("alert-danger");
        $("#alertDiv").delay(5000).hide(0, function () {
            $(this).remove();
        });
    }
    $("#alertDiv button").click(function () {
        onclick = $("#alertDiv").fadeOut();
    })
};

//***************************************
// 清空Form表单并隐藏对话框
// targetForm: 需要清空的对话框并隐藏
// targetModal: 需要隐藏的对话框
//***************************************
$.clearModal = function (targetForm, targetModal) {
    targetForm.bootstrapValidator('resetForm', true);
    $(':input', targetForm)
        .not(':button, :submit, :reset')
        .val('')
        .removeAttr('checked')
        .removeAttr('selected');
    targetModal.modal("hide");
};

$.showPicModal = function (jsonData) {
    $("#showPicture").attr("src", jsonData);
    $("#showPicLabel").text("图片");
    $("#showPicModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

var customTemplates = {
    image: function (context) {
        return "<li>" +
            "<a class='btn btn-default' data-wysihtml5-command='insertImage' title='" + context.locale.image.insert +
            "' tabindex='-1' onclick='$.uploadFeedBackPhoto()'><span class='glyphicon glyphicon-picture'></span></a>" +
            "</li>";
    }
};

$("#feedBackContent").wysihtml5({
    customTemplates: customTemplates
});

$.feedBack = function () {
    $("#modal-feedBack").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$.addFeedBack = function () {
    if ($("#feedBackContent").val() == 0)
        $.alert("请填写内容", 2);
    else {
        bootbox.confirm({
            buttons: {
                confirm: {
                    label: '<i class="fa fa-check"></i> 确定',
                    className: 'btn btn-primary btn-flat'
                },
                cancel: {
                    label: '<i class="fa fa-close"></i> 取消',
                    className: 'btn btn-warning btn-flat pull-left'
                }
            },
            message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定提交该反馈吗?</b>',
            callback: function (result) {
                if (result) {
                    $.ajax({
                        url: "../rds_feedback/addFeedBack",
                        type: "post",
                        dataType: "json",
                        data: {
                            rapporteurId: gUserLoginResult.userId,
                            feedBackCreateTime: $.getTime(),
                            feedBackContent: $("#feedBackContent").val()
                        },
                        success: function () {
                            $.alert("发送成功！", 1);
                            $.closeFeedBack();
                        },
                        error: function () {
                            $.alert("系统错误！", 4);
                        }
                    });
                }
            }
        });
    }

};

$.closeFeedBack = function () {
    $('#feedBackContent').parent().find('.wysihtml5-toolbar').remove();
    $('#feedBackContent').parent().find('iframe').remove();
    $('#feedBackContent').parent().find('input[name*="wysihtml5"]').remove();
    $('#feedBackContent').show();
    $('#feedBackContent').val("");
    $("#modal-feedBack").modal("hide");
    $("#feedBackContent").wysihtml5();
};

// 打开上传modal框
$.uploadFeedBackPhoto = function () {
    $("#upFeedBackPictureModal").modal({
        backdrop: 'static',
        keyboard: true,
        show: true
    });
};

// 关闭上传modal框
$.closeUpFeedBackPtModal = function () {
    $("#upFeedBackPictureModal").modal("hide");
    $("#ossfile").empty();
    clearOssData();
};

//获取图片信息
$.doneUpFeedBackPicture = function () {
    var fileInfo = getOssFileInfo();
    if (fileInfo.length == 0) {
        $.alert("未上传图片", 2);
    } else if (fileInfo.length > 1) {
        $.alert("只需上传一张图片作为证明材料", 3);
    } else {
        $.addImageFeedBack(fileInfo[0].fileUrl);
        $.closeUpFeedBackPtModal();
    }
};

$.addImageFeedBack = function (newUrl) {
    var str = $('#feedBackContent').val();
    $('#feedBackContent').parent().find('.wysihtml5-toolbar').remove();
    $('#feedBackContent').parent().find('iframe').remove();
    $('#feedBackContent').parent().find('input[name*="wysihtml5"]').remove();
    $('#feedBackContent').show();
    if (str.indexOf("<img>") != 0)
        str = str.substring(0, str.indexOf("<img>") + 4) +
            "  width=300px src = '" + newUrl + "'/ " +
            str.substring(str.indexOf("<img>") + 4);
    $('#feedBackContent').val(str);
    $("#feedBackContent").wysihtml5();
};


//判断文件类型(在需要的js文件添加，文件名务必保持一致)
function judgeFileType(suffix) {
    //图片文件
    if (!(suffix == ".jpg" || suffix == ".JPG" || suffix == ".png" || suffix == ".PNG" ||
            suffix == ".jpeg" || suffix == ".JPEG" || suffix == ".gif" || suffix == ".GIF" ||
            suffix == ".bmp" || suffix == ".BMP")) {
        alert("请选择图片文件！");
        return false;
    }
}

$.getTime = function () {
    $.changeTimeType = function (date) {
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }
        return date;
    };
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = $.changeTimeType(date.getMonth() + 1);
    var strDate = $.changeTimeType(date.getDate());
    var hour = $.changeTimeType(date.getHours());
    var minutes = $.changeTimeType(date.getMinutes());
    var seconds = $.changeTimeType(date.getSeconds());

    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + hour + seperator2 + minutes
        + seperator2 + seconds;
    return currentdate;
};

function _debounce(fn, delay) {

    // 定时器，用来 setTimeout
    var timer

    // 返回一个函数，这个函数会在一个时间区间结束后的 delay 毫秒时执行 fn 函数
    return function () {

        // 保存函数调用时的上下文和参数，传递给 fn
        var context = this
        var args = arguments

        // 每次这个返回的函数被调用，就清除定时器，以保证不执行 fn
        clearTimeout(timer)

        // 当返回的函数被最后一次调用后（也就是用户停止了某个连续的操作），
        // 再过 delay 毫秒就执行 fn
        timer = setTimeout(function () {
            fn.apply(context, args)
        }, delay)
    }
}



function formatDateTime(inputTime) {
    var len=inputTime.length;
    if(len===10)//转成毫秒时间戳
        inputTime=inputTime*1000;
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}